package com.wswy.wzcx.ui.main;

import android.Manifest;
import android.Manifest.permission;
import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.airbnb.lottie.LottieAnimationView;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.che.libcommon.ui.NavTabController;
import com.che.libcommon.utils.ToastUtils;
import com.che.libcommon.widget.BottomNavLayout;
import com.che.libcommon.widget.BottomNavLayout.BottomItem;
import com.che.libcommon.widget.BottomNavLayout.ItemViewProvider;
import com.che.libcommon.widget.BottomNavLayout.OnTabSelectedListener;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tuia.ad.Ad;
import com.wswy.wzcx.BuildConfig;
import com.wswy.wzcx.R;
import com.wswy.wzcx.api.ConfigsKt;
import com.wswy.wzcx.model.MessageMode;
import com.wswy.wzcx.model.UpgradeModel;
import com.wswy.wzcx.model.home.RPaths;
import com.wswy.wzcx.model.home.RouterUtils;
import com.wswy.wzcx.model.license.UserCarInfo;
import com.wswy.wzcx.module.ChannelManager;
import com.wswy.wzcx.module.GlobalConfigManager;
import com.wswy.wzcx.module.LocManager;
import com.wswy.wzcx.module.MessageCenter;
import com.wswy.wzcx.module.MessageCenter.UnreadCount;
import com.wswy.wzcx.module.RuntimeContext;
import com.wswy.wzcx.module.UserDataProvider;
import com.wswy.wzcx.module.base.CBaseActivity;
import com.wswy.wzcx.module.base.CBaseFragment;
import com.wswy.wzcx.module.upgrade.UpgradeConfigure;
import com.wswy.wzcx.push.PushExtras;
import com.wswy.wzcx.statistics.StatTools;
import com.wswy.wzcx.statistics.StatisticsId;
import com.wswy.wzcx.ui.Constants;
import com.wswy.wzcx.ui.activity.MineActivity;
import com.wswy.wzcx.ui.car.result.QueryResultActivity;
import com.wswy.wzcx.ui.dialog.ExitDialog;
import com.wswy.wzcx.ui.dialog.WarningDialog;
import com.wswy.wzcx.ui.main.ad.HomeAdViewModel;
import com.wswy.wzcx.ui.main.common.HomeFKDJFragment;
import com.wswy.wzcx.ui.main.common.UpgradeDialog;
import com.wswy.wzcx.ui.main.community.CommunityFragment;
import com.wswy.wzcx.ui.main.garage.GarageFragment;
import com.wswy.wzcx.ui.main.home.HomeFragment;
import com.wswy.wzcx.ui.main.mine.MainMineFragment;
import com.wswy.wzcx.ui.main.news.MainNewsFragment;
import com.wswy.wzcx.ui.message.MessageDetailFragment;
import com.wswy.wzcx.ui.other.AdUtils;
import com.wswy.wzcx.ui.other.SimpleHttp;
import com.wswy.wzcx.ui.other.UpdateTools;
import com.wswy.wzcx.ui.web.Traffic12123Fragment;
import com.wswy.wzcx.ui.web.WebPageArgument;
import com.wswy.wzcx.utils.StringUtils;
import com.wswy.wzcx.utils.UiUtils;
import com.wswy.wzcx.utils.UnicornManager;
import com.wswy.wzcx.widget.NewbieGuideLayout;
import com.wswy.wzcx.widget.NewbieGuideLayout.GuideItem;

import io.reactivex.observers.ResourceObserver;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function2;

public class MainActivity extends CBaseActivity implements NavTabController.FragmentProvider,
        IScrollTopHandler, NewbieIndexHandler {

    private static final String APP_CACHE_DIRNAME = "/webcache"; // web缓存目录
    private static final String TAG = "MainActivity";

    private static final String SP_NEWBIE = "key_newbie_guide_ver";

    private static final String TAG_HOME = "home";
    //private static final String TAG_BOOK = "book";
    private static final String TAG_12123 = "12123_web";
    private static final String TAG_COMMUNITY = "bbs";
    private static final String TAG_MINE = "mine";
    private static final String TAG_CARS = "cars";

    private static final String TAG_FKDJ = "fkdj";

    private static final String TAG_NEWS = "news";

    private BottomNavLayout bottomNavLayout;

    private NavTabController navTabController;

    private ImageView imgTop;

    private View mineUnreadSign;

    private InnerBottomState lastBottomState = new InnerBottomState();

    private Ad tuiaAd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (!TextUtils.isEmpty(BuildConfig.TUIA_APPKEY)) {
            tuiaAd = new Ad(BuildConfig.TUIA_APPKEY, "310411");
            tuiaAd.init(this, null, null);
        }

        bottomNavLayout = findViewById(R.id.bottom_navigation);
        imgTop = findViewById(R.id.img_top);

        UiUtils.INSTANCE.setStatusBarLight(this, true);

        //加载广告
        provideViewModel(HomeAdViewModel.class).loadAD(this);
        navTabController = new NavTabController(this, getSupportFragmentManager(),
                R.id.fragment_container);
        navTabController.show(TAG_HOME);
        List<BottomItem> items = new ArrayList<>();
        items.add(new BottomItem(R.string.nav_home, R.drawable.nav_home_nor, R.raw.home_pre, TAG_HOME));

        items.add(new BottomItem(R.string.nav_garage, R.drawable.nav_cheku_nor, R.raw.cheku_pre, TAG_CARS));

        // items.add(new BottomItem(R.string.nav_fkdj, R.drawable.nav_fkdj, TAG_FKDJ));
//    items.add(new BottomItem(R.string.nav_recommend, R.drawable.nav_choice, ChoiceFragment.class));
        //items.add(new BottomItem(R.string.nav_12123, R.drawable.nav_12123, TAG_12123));

        items.add(new BottomItem(R.string.nav_news, R.drawable.nav_news_nor, R.raw.news_pre, TAG_NEWS));
        //items.add(new BottomItem(R.string.nav_community, R.drawable.nav_community, TAG_COMMUNITY));
        items.add(new BottomItem(R.string.nav_mine, R.drawable.nav_mine_nor, R.raw.mine_pre, TAG_MINE));
        bottomNavLayout.setItems(items, new ItemViewProvider() {
            @Override
            public View getView(ViewGroup parent, View convertView, int position, BottomItem item) {
                if (convertView == null) {
                    convertView = getLayoutInflater().inflate(R.layout.item_main_nav_layout, parent, false);
                    ImageView imageView = convertView.findViewById(R.id.img_icon);
                    TextView textView = convertView.findViewById(R.id.tv_title);
                    imageView.setImageResource(item.drawableRes);
                    textView.setText(item.titleRes);

                    if (position == 0) {
                        LottieAnimationView view = (LottieAnimationView) imageView;
                        view.setAnimation(item.animRes);
                        view.playAnimation();
                        lastBottomState.save(view, item, 0);
                    }
                } else {

                    TextView textView = convertView.findViewById(R.id.tv_title);
                    ImageView imageView = convertView.findViewById(R.id.img_icon);
                    if (lastBottomState.position == position) {
                        LottieAnimationView view = (LottieAnimationView) imageView;
                        view.setAnimation(item.animRes);
                        view.playAnimation();
                        lastBottomState.save(view, item, 0);
                    } else {

                        imageView.setImageResource(item.drawableRes);
                    }
                    textView.setText(item.titleRes);
                }
                if (TAG_MINE.equals(item.tag)) {
                    mineUnreadSign = convertView.findViewById(R.id.view_sign);
                }

                return convertView;
            }
        });


        bottomNavLayout.setOnTabSelectedListener(new OnTabSelectedListener() {
            @Override
            public void onSelected(View view, BottomItem item) {
                if (VERSION.SDK_INT >= VERSION_CODES.M) {
//              if (TextUtils.equals(item.tag,TAG_MINE)){
//                UiUtils.INSTANCE.setStatusBarLight(MainActivity.this,false);
//              }else {
//                UiUtils.INSTANCE.setStatusBarLight(MainActivity.this,true);
//              }
                    if (!TAG_12123.equals(item.tag) && !TAG_HOME.equals(item.tag) && !TAG_NEWS.equals(item.tag)) {
                        UiUtils.INSTANCE.setStatusBarLight(MainActivity.this, false);
                    } else {
                        UiUtils.INSTANCE.setStatusBarLight(MainActivity.this, true);
                    }
                }
                lastBottomState.restore();
                View imgView = view.findViewById(R.id.img_icon);
                if (imgView instanceof LottieAnimationView) {
                    //修改动画
                    LottieAnimationView bottomImg = (LottieAnimationView) imgView;
                    bottomImg.setAnimation(item.animRes);
                    bottomImg.playAnimation();
                    lastBottomState.save(bottomImg, item, bottomNavLayout.getSelectedPosition());
                }

                if (!TAG_HOME.equals(item.tag)) {
                    onHideTop();
                } else {
                    Fragment fragment = navTabController.findFragment(item.tag);
                    if (fragment instanceof IScrollTopChild) {
                        if (imgTop.isShown()) {
                            ((IScrollTopChild) fragment).scrollTop();
                        } else {
                            if (((IScrollTopChild) fragment).isShowTop()) {
                                onShowTop();
                            } else {
                                onHideTop();
                            }
                        }

                    }

                }

                navTabController.show(item.tag);
                StatTools.sendClick(MainActivity.this, TextUtils.concat("click_", item.tag).toString());
            }
        });


        MainActUtils.addNextDialog(MainActUtils.DLG_KEY_POLICY, new Runnable() {
            @Override
            public void run() {
                showPrivacyPolicy();
            }
        });

        //showPrivacyPolicy();
        requestPermissions();
//        SharedPrefStorage.readMessage(DataCenter.KEY_LOCAL_CHECK_UPDATE_TIME, 0L)
//                .subscribe(new SingleObserver<Long>() {
//                    @Override
//                    public void onSubscribe(Disposable d) {
//
//                    }
//
//                    @Override
//                    public void onSuccess(Long aLong) {
//                        long currentTime = System.currentTimeMillis();
//                        if (currentTime - aLong > 24 * 60 * 60 * 1000) {
//                            checkUpdate();
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//                });
        handlerPush();
        initScrollTop();
        //listener();

//        int newbieVer = SPUtils.getInstance().getInt(SP_NEWBIE,0);
//
//        if (newbieVer < BuildConfig.VERSION_CODE) {
//            SPUtils.getInstance().put(SP_NEWBIE,BuildConfig.VERSION_CODE);
//            UiUtils.INSTANCE.addOnGlobalLayoutListener(findViewById(R.id.layout_bottom),
//                new Function1<View, Unit>() {
//                    @Override
//                    public Unit invoke(View view) {
//                        initNewbie(view.getTop(), view.getHeight());
//                        return null;
//                    }
//                });
//        }

    }

    public void showNewbieWeather(Rect rect) {

    }

    //初始化 新版本指引
    private void initNewbie(int top, int height) {
        final ViewGroup viewGroup = findViewById(R.id.layout_root);
        final NewbieGuideLayout guideLayout = new NewbieGuideLayout(this);
        viewGroup.addView(guideLayout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        List<NewbieGuideLayout.GuideItem> items = new ArrayList<>();
        int w = ScreenUtils.getScreenWidth() / 4;
        RectF baseRect = new RectF(0, top, w, top + height);
//        for (int i = 0; i < 4; i++) {
//            RectF rect = new RectF(baseRect);
//            rect.offset(w*i,0);
//            items.add(new NewbieGuideLayout.GuideItem(rect,R.drawable.guide_car_2,"新增车库，车主服务更方便"));
//        }
        //只有第一个
        RectF rect = new RectF(baseRect);
        rect.offset(w * 2, 0);
        //items.add(new NewbieGuideLayout.GuideItem(rect,R.drawable.guide_car_2,"新增车库，车主服务更方便"));
        items.add(new NewbieGuideLayout.GuideItem(rect,
                R.drawable.guide_tucao_3,
                "吐槽、话题社交精彩不断", GuideItem.Companion.getCIRCLE(),
                Color.parseColor("#6150FF"),
                Color.parseColor("#5786FF")
        ));
        guideLayout.setGuideItem(items);

        guideLayout.setStepEndCallback(new Function1<View, Unit>() {
            @Override
            public Unit invoke(View view) {
                viewGroup.removeViewInLayout(view);
                return null;
            }
        });


    }

    private void initScrollTop() {
        final View homeIcon = bottomNavLayout.getChildAt(0).findViewById(R.id.img_icon);
        UiUtils.INSTANCE.addOnGlobalLayoutListener(homeIcon,
                new OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        Rect rect = new Rect();
                        homeIcon.getGlobalVisibleRect(rect);
                        int imgW = imgTop.getWidth();
                        int imgH = imgTop.getHeight();
                        if (imgW == 0 || imgH == 0) {
                            imgTop.measure(0, 0);
                            imgW = imgTop.getMeasuredWidth();
                            imgH = imgTop.getMeasuredHeight();
                        }

                        int left = rect.centerX() - imgW / 2;
                        int top = rect.bottom - imgH;
                        LayoutParams layoutParams = imgTop.getLayoutParams();
                        if (layoutParams instanceof MarginLayoutParams) {
                            ((MarginLayoutParams) layoutParams).topMargin = top;
                            ((MarginLayoutParams) layoutParams).leftMargin = left;
                            imgTop.setLayoutParams(layoutParams);
                        }
                    }
                });
    }


    private Observer<UpgradeModel> upgradeModelObserver;
    private Observer<UnreadCount> unreadCountObserver;

    private void listener() {
        if (upgradeModelObserver == null) {
            //应用更新
            upgradeModelObserver = new Observer<UpgradeModel>() {
                @Override
                public void onChanged(@Nullable UpgradeModel upgradeModel) {
                    //有更新
                    try {
                        if (upgradeModel != null) {
                            if (upgradeModel.getShowMarketDialog()) {
                                //支持本地打开
                                showUpgradeDialog(upgradeModel);
                            } else {
                                //不支持本地打开  bugly检查更新
                                UpgradeConfigure.checkUpgrade(true, false);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        MainActUtils.checkAndShow(true);
                    }
                }
            };
            MessageCenter.INSTANCE.getMainUpgradeLiveData().observeForever(
                    upgradeModelObserver);
        }


        if (unreadCountObserver == null) {
            //未读通知
            unreadCountObserver = new Observer<UnreadCount>() {
                @Override
                public void onChanged(@Nullable UnreadCount unreadCount) {
                    if (unreadCount != null && mineUnreadSign != null) {
                        int count = unreadCount.getFeedback() + unreadCount.getMsg();

                        try {
                            if (count > 0) {
                                mineUnreadSign.setVisibility(View.VISIBLE);
                            } else {
                                mineUnreadSign.setVisibility(View.INVISIBLE);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }


                }
            };
            MessageCenter.INSTANCE.getAllUnreadLiveData().observeForever(unreadCountObserver);
        }


    }

    private void removeObserves() {
        if (upgradeModelObserver != null) {
            MessageCenter.INSTANCE.getMainUpgradeLiveData().removeObserver(upgradeModelObserver);
            upgradeModelObserver = null;
        }
        if (unreadCountObserver != null) {
            MessageCenter.INSTANCE.getAllUnreadLiveData().removeObserver(unreadCountObserver);
            unreadCountObserver = null;
        }

    }


    private void handlerPush() {
        Intent intent = getIntent();
        if (null != intent) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null) {
                String startFrom = bundle.getString(PushExtras.START_FROM, null);
                if (!TextUtils.isEmpty(startFrom)) {
                }
                String target = bundle.getString(PushExtras.TARGET, null);
                if (TextUtils.isEmpty(target)) {
                    return;
                }

                if (TextUtils.equals("messageDetailServer", target)) {
                    startActivity(MineActivity.asIntent(this, MessageDetailFragment.TAG, MessageMode.MESSAGE_USER));
                    SimpleHttp.INSTANCE.setReader(MessageMode.MESSAGE_USER);
                } else if (TextUtils.equals("messageDetailActivity", target)) {
                    startActivity(MineActivity
                            .asIntent(this, MessageDetailFragment.TAG, MessageMode.MESSAGE_SYSTEM));
                    SimpleHttp.INSTANCE.setReader(MessageMode.MESSAGE_SYSTEM);
                } else if (TextUtils.equals("web", target)) {
                    //打开h5页面
                    String url = bundle.getString(PushExtras.URL);
                    String title = bundle.getString(PushExtras.TITLE);
                    if (!TextUtils.isEmpty(url)) {
                        //检测链接
//                        if (TextUtils.isEmpty(title)) {
//
//                        } else {
//                            WebViewActivity.startWebview(this, title, url, true);
//                        }
                        WebPageArgument argument = new WebPageArgument(url);
                        if (TextUtils.isEmpty(title)) {
                            argument.setTitle("热门资讯");
                        } else {
                            argument.setTitle(title);
                        }
                        argument.setShowToolBar(true);
                        argument.setShowUrlTitle(false);
                        if (AdUtils.showBannerAd(url)) {
                            argument.setShowBannerAd(true);
                        }
                        RouterUtils.startWeb(this, argument);
                    }

                } else {
                    //查找本地支持打开的页面
                    intent = RouterUtils.getIntent(this, RouterUtils.TYPE_NATIVE, target);
                    if (intent != null) {
                        //支持本地打开的类型

                        if (RouterUtils.needCarId(target)) {
                            //需要车辆id

                            int carId = StringUtils.parseInt(bundle.getString(PushExtras.USER_CAR_ID), 0);
                            if (carId > 0) {

                                if (TextUtils.equals(RPaths.carQuery, target)) {
                                    //车辆违章  特殊处理
                                    QueryResultActivity.start(this, carId, -1);
                                } else if (TextUtils.equals(RPaths.wzdbChooseCar, target)) {
                                    //违章代办，选择车辆信息
                                    UserCarInfo carInfo = UserDataProvider.get().getUserCarInfo(carId);
                                    if (carInfo != null) {
                                        intent.putExtra(Constants.EXTRA_DATA, carInfo);
                                        startActivity(intent);
                                    }

                                } else {
                                    intent.putExtra(Constants.EXTRA_USER_CAR_ID, carId);
                                    startActivity(intent);
                                }

                            }
                        } else if (RouterUtils.needTopicId(target)) {
                            long topicId = StringUtils.parseLong(bundle.getString(PushExtras.TOPIC_ID), 0);
                            if (topicId > 0) {
                                intent.putExtra(Constants.EXTRA_DATA_ID, topicId);
                                startActivity(intent);
                            }

                        } else {

                            if (RPaths.social_msg_list.equals(target)) {
                                SimpleHttp.INSTANCE.setReader(MessageMode.MESSAGE_SOCIAL);
                            }
                            //罚款代缴
                            if (TextUtils.equals(RPaths.fkdj, target)) {
                                intent.putExtra(Constants.EXTRA_DATA, bundle.getString(PushExtras.FINE_NO));
                            }
                            startActivity(intent);
                        }


                    } else {
                        //找不到本地打开的类型，将页面tab切换到首页

                        if (navTabController != null) {

                            bottomNavLayout.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    bottomNavLayout.setSelectedPosition(0, true);
                                }
                            }, 100);


                        }
                    }

                }

            }
        }
    }

    //显示隐私协议
    private void showPrivacyPolicy() {
        boolean user_agree_to_policy = SPUtils.getInstance()
                .getBoolean("user_agree_to_policy", false);
        //已经同意 不弹窗
        if (user_agree_to_policy) {
            MainActUtils.checkAndShow(true);
            return;
        }

        SpannableStringBuilder sb = new SpannableStringBuilder();
        SpannableString content = new SpannableString("欢迎使用交通在线App！\n为帮助您安全使用本产品提供的相关服务，请您在下方点击查看完整版");
        content.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.textColorPrimary_70)), 0, content.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        sb.append(content);


        SpannableString service1 = new SpannableString("《用户服务协议》");
        service1.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.colorPrimary)), 0, service1.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        service1.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                if (TextUtils.equals(ChannelManager.getChannel(), "huawei")) {
                    RouterUtils.startWeb(widget.getContext(), ConfigsKt.INSTANCE.getH5_TERMS_OF_SERVICE()+"?platform=jtzx");
                    return;
                }
                RouterUtils.startWeb(widget.getContext(), ConfigsKt.INSTANCE.getH5_TERMS_OF_SERVICE());
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(false);
                ds.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
                ds.clearShadowLayer();
            }
        }, 0, service1.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        sb.append(service1);

        content = new SpannableString("及");
        content.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.textColorPrimary_70)), 0, content.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        sb.append(content);

        SpannableString service = new SpannableString("《隐私政策》");
        service.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.colorPrimary)), 0, service.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        service.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                if (TextUtils.equals(ChannelManager.getChannel(), "huawei")) {
                    RouterUtils.startWeb(widget.getContext(), ConfigsKt.INSTANCE.getH5_PRIVACY_POLICY()+"?platform=jtzx");
                    return;
                }
                RouterUtils.startWeb(widget.getContext(), ConfigsKt.INSTANCE.getH5_PRIVACY_POLICY());
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {

                super.updateDrawState(ds);
                ds.setUnderlineText(false);
                ds.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary));
                ds.clearShadowLayer();
            }
        }, 0, service.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        sb.append(service);

        content = new SpannableString("。并确认您已了解我们对您个人信息的处理方式。\n");
        content.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.textColorPrimary_70)), 0, content.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        sb.append(content);

        SpannableString hint = new SpannableString("点击『同意』，开始使用本产品，我们将尽力保护您的隐私信息。");
        hint.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.textColorPrimary_40)), 0, hint.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        sb.append(hint);


        SpannableString sbp = new SpannableString("交通在线坚决保障您的隐私信息安全，您的信息仅用于为您提供服务或改善服务体验。如您确实无法认同此政策，可退出应用。");


        final String title = "用户隐私协议说明";
        final String title2 = "隐私保护提示";

        final CharSequence msg = sb;
        final CharSequence msg2 = sbp;

        final String leftText = "不同意";
        final String rightText = "同意";


        final String leftText2 = "退出应用";
        final String rightText2 = "返回";


        final WarningDialog warningDialog = new WarningDialog(this, msg);

        warningDialog.setActionDismiss(false);
        warningDialog.setTextConfigure(new Function1<TextView, Unit>() {
            @Override
            public Unit invoke(TextView textView) {

                textView.setHighlightColor(Color.TRANSPARENT);
                textView.setMovementMethod(LinkMovementMethod.getInstance());

                return null;
            }
        });
        warningDialog.setCancelClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (TextUtils.equals(warningDialog.getCancelText(), leftText2)) {

                    warningDialog.dismiss();
                    finish();
                } else {
                    warningDialog.updateText(title2, msg2, leftText2, rightText2);
                }


            }
        });
        warningDialog.setClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.equals(warningDialog.getButtonText(), rightText)) {
                    SPUtils.getInstance().put("user_agree_to_policy", true);
                    MainActUtils.checkAndShow(true);
                    warningDialog.dismiss();
                } else {
                    //返回
                    warningDialog.updateText(title, msg, leftText, rightText);
                }


            }
        });
        warningDialog.setCancelText(leftText);
        warningDialog.setButtonText(rightText);
        warningDialog.setTitle(title);

        warningDialog.show();
    }

    private void showUpgradeDialog(@NonNull final UpgradeModel upgradeModel) {
        MainActUtils.addNextDialog(MainActUtils.DLG_KEY_UPDATE, new Runnable() {
            @Override
            public void run() {
                UpgradeDialog dialog = new UpgradeDialog(MainActivity.this, upgradeModel);
                dialog.setOnUpgradeCallback(new Function2<UpgradeModel, Integer, Unit>() {
                    @Override
                    public Unit invoke(UpgradeModel upgradeModel, Integer type) {
                        if (type >= 1) {
                            //点击了更新
                            StatTools.sendShow(getApplicationContext(), StatisticsId.upgrade_click, upgradeModel.getJumpMarket());
                            UpdateTools.INSTANCE.startMarket(MainActivity.this, upgradeModel);
                        }
                        if (type != 2) {
                            //非强制更新
                            MainActUtils.checkAndShow(true);
                        }
                        if (type == 0) {
                            //取消
                            StatTools.sendShow(getApplicationContext(), StatisticsId.upgrade_click, "cancel");
                        }

                        return null;
                    }
                });
                dialog.show();
            }
        });

    }


//    private void checkUpdate() {
//        Single.timer(2000, TimeUnit.MILLISECONDS)
//                .flatMap((Function<Long, SingleSource<Optional<VersionModel>>>) aLong -> Api.get().checkVersionInfo()).subscribe(new ApiOptionalResultObserver<VersionModel>() {
//            @Override
//            protected void onApiResult(@Nullable VersionModel value) {
//                if (value != null && BuildConfig.VERSION_CODE < value.getVersionCode()) {
//                    UpdateTools.start(MainActivity.this, value);
//                    SharedPrefStorage.writeMessage(DataCenter.KEY_LOCAL_CHECK_UPDATE_TIME, System.currentTimeMillis());
//                }
//            }
//
//            @Override
//            protected void onApiError(@Nullable BaseResult result) {
//
//            }
//        });
//    }

    @Override
    public Fragment getFragment(String tag) {
        Fragment fragment = null;

        switch (tag) {
            case TAG_HOME:
                fragment = new HomeFragment();
                break;
            case TAG_CARS:
                fragment = new GarageFragment();
                break;
            case TAG_COMMUNITY:
                fragment = new CommunityFragment();
                break;
            case TAG_12123:
                fragment = Traffic12123Fragment.newInstance();
                break;
            case TAG_FKDJ:
                fragment = new HomeFKDJFragment();
                break;
            case TAG_MINE:
                fragment = new MainMineFragment();
                break;
            case TAG_NEWS:
                fragment = new MainNewsFragment();
                break;
        }

        return fragment;
    }


    private void requestPermissions() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.requestEach(permission.READ_PHONE_STATE,
                //permission.WRITE_EXTERNAL_STORAGE,
                //permission.CAMERA,
                permission.ACCESS_COARSE_LOCATION)
                .subscribe(new ResourceObserver<Permission>() {
                    @Override
                    public void onNext(Permission permission) {

                        //获取位置
                        if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permission.name) && permission.granted) {
                            LocManager.getInstance().loadLocation();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected boolean autoHackStatusBar() {
        return false;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable("android:support:fragments", null);
    }


    @Override
    public void onBackPressed() {
        if (navTabController.isShowing(TAG_HOME)) {

            if (RuntimeContext.isPaidChannel()) {
                //付费推广渠道
                new ExitDialog(this, new Function0<Unit>() {
                    @Override
                    public Unit invoke() {

                        MainActivity.super.onBackPressed();

                        return null;
                    }
                }).show();
            } else {
                super.onBackPressed();
            }

        } else if (navTabController.isShowing(TAG_FKDJ)) {
            //罚款代缴
            Fragment currentFragment = navTabController.getCurrentFragment();
            boolean handle = false;
            if (currentFragment instanceof CBaseFragment) {
                handle = ((CBaseFragment) currentFragment).onBackPress();
            }
            if (!handle) {

                bottomNavLayout.setSelectedPosition(0, true);
            }
        } else {
            bottomNavLayout.setSelectedPosition(0, true);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handlerPush();
    }

    @Override
    public void onShowTop() {
        imgTop.setVisibility(View.VISIBLE);
        bottomNavLayout.updateItem(0, R.string.scroll_top);
    }

    @Override
    public void onHideTop() {
        imgTop.setVisibility(View.INVISIBLE);
        bottomNavLayout.updateItem(0, R.string.nav_home);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean handle = false;
        if (tuiaAd != null) {
            handle = tuiaAd.onKeyBack(keyCode, event);
        }

        return handle || super.onKeyDown(keyCode, event);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeObserves();
        lastBottomState.release();
        MainActUtils.dlgEnd();
        if (tuiaAd != null) {
            tuiaAd.destroy();
        }

        UnicornManager.logout();
    }

    @Override
    public boolean needCap() {
//        boolean need = false;
//
//        int newbieVer = SPUtils.getInstance().getInt(SP_NEWBIE,0);
//        if (newbieVer < BuildConfig.VERSION_CODE) {
//            SPUtils.getInstance().put(SP_NEWBIE,BuildConfig.VERSION_CODE);
//            need = true;
//        }
//
//        return need;
        return false;
    }

    @Override
    public void capScreen(RectF rectF) {

        final ViewGroup viewGroup = findViewById(R.id.layout_root);

        final NewbieGuideLayout guideLayout = new NewbieGuideLayout(this);

        viewGroup.addView(guideLayout, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

        List<NewbieGuideLayout.GuideItem> items = new ArrayList<>();
        items.add(new NewbieGuideLayout.GuideItem(rectF,
                R.drawable.guide_weather,
                "点击查看天气详情",
                GuideItem.Companion.getROUND_RECT(),
                Color.parseColor("#25C495"),
                Color.parseColor("#82E86A")
        ));
        guideLayout.setGuideItem(items);

        guideLayout.setStepEndCallback(new Function1<View, Unit>() {
            @Override
            public Unit invoke(View view) {

                viewGroup.removeViewInLayout(view);

                return null;
            }
        });


    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        MainActUtils.report();
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        MainActUtils.report();
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        listener();
        MainActUtils.report();
        GlobalConfigManager.getInstance().reloadConfig();
        MessageCenter.INSTANCE.mainCheckUpgrade(false);
    }

    @Override
    protected void onPause() {
        super.onPause();
        removeObserves();
    }

    public Ad getTuiaAd() {
        return tuiaAd;
    }

    private static class InnerBottomState {
        WeakReference<LottieAnimationView> bottomImageView;
        BottomItem bottomItem;
        int position;

        void save(LottieAnimationView view, BottomItem item, int position) {
            bottomImageView = new WeakReference<>(view);
            bottomItem = item;
            this.position = position;
        }


        void restore() {

            LottieAnimationView lottieAnimationView = null;

            if (bottomImageView != null && (lottieAnimationView = bottomImageView.get()) != null && bottomItem != null) {
                lottieAnimationView.setImageResource(bottomItem.drawableRes);
            }
            release();
        }

        void release() {
            bottomImageView.clear();
            bottomImageView = null;
            bottomItem = null;
            position = -1;
        }
    }

}
